package com.dream21th.admin.controller;

import com.dream21th.admin.common.PasswordForm;
import com.dream21th.admin.entity.SysUserEntity;
import com.dream21th.admin.entity.SysUserTokenEntity;
import com.dream21th.admin.service.ShiroService;
import com.dream21th.admin.service.SysUserRoleService;
import com.dream21th.admin.service.SysUserService;
import com.dream21th.admin.service.SysUserTokenService;
import com.dream21th.admin.utils.Constant;
import com.dream21th.admin.utils.PageUtils;
import com.dream21th.common.ComResp;
import com.dream21th.common.dto.UserDTO;
import com.dream21th.common.dto.UserTokenDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.base.Preconditions;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;


@RestController
@RequestMapping("/sys/user")
public class SysUserController extends BaseUserController{

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private SysUserRoleService sysUserRoleService;

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Autowired
	private ShiroService shiroService;

	@Autowired
	private SysUserTokenService sysUserTokenService;

	/**
	 * 所有用户列表
	 */
	@PostMapping("/list")
	public ComResp<PageUtils> list(@RequestBody Map<String, Object> params, Authentication authentication){
		//只有超级管理员，才能查看所有管理员列表
		Long loginUserId=loginUserId(authentication);
		if(loginUserId != Constant.SUPER_ADMIN){
			params.put("createUserId", loginUserId);
		}
		PageUtils page = sysUserService.queryPage(params);
		return new ComResp<PageUtils>().data(page).success();
	}

	/**
	 * 获取登录的用户信息
	 */
	@PostMapping("/info")
	public ComResp<UserDTO> info(Authentication authentication){
		String username = (String)authentication.getPrincipal();
		SysUserEntity sysUserEntity = sysUserService.queryByUserName(username);
		UserDTO build = UserDTO.builder().build();
		BeanUtils.copyProperties(sysUserEntity,build);
		return new ComResp<UserDTO>().data(build).success();
	}

	/**
	 * 修改登录用户密码
	 */
	@PostMapping("/password")
	public ComResp password(@RequestBody PasswordForm form,Authentication authentication){
		Preconditions.checkArgument(!Objects.isNull(form.getNewPassword()), "新密码不为能空");

		SysUserEntity sysUserEntity = loginUser(authentication);
		if(!passwordEncoder.matches(form.getPassword(),sysUserEntity.getPassword())){
			return new ComResp().result("500","原密码不正确");
		}
		String newPassword = passwordEncoder.encode(form.getNewPassword());

		//更新密码
		boolean flag = sysUserService.updatePassword(sysUserEntity.getUserId(), sysUserEntity.getPassword(), newPassword);

		return new ComResp().success();
	}

	/**
	 * 用户信息
	 */
	@PostMapping("/infoByUserId")
	public ComResp<SysUserEntity> info(@RequestBody UserDTO userDTO){
		SysUserEntity user = sysUserService.getById(userDTO.getUserId());
		//获取用户所属的角色列表
		List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userDTO.getUserId());
		user.setRoleIdList(roleIdList);
		return new ComResp<SysUserEntity>().data(user).success();
	}

	/**
	 * 保存用户
	 */
	@PostMapping("/save")
	public ComResp save(@RequestBody SysUserEntity user,Authentication authentication){
		user.setCreateUserId(loginUserId(authentication));
		sysUserService.saveUser(user);

		return new ComResp().success();
	}

	/**
	 * 修改用户
	 */
	@PostMapping("/update")
	public ComResp update(@RequestBody SysUserEntity user,Authentication authentication){

		user.setCreateUserId(loginUserId(authentication));
		sysUserService.update(user);

		return new ComResp().success();
	}

	/**
	 * 删除用户
	 */
	@PostMapping("/delete")
	public ComResp delete(@RequestBody Long[] userIds,Authentication authentication){
		if(ArrayUtils.contains(userIds, 1L)){
			return new ComResp().result("500","系统管理员不能删除");
		}

		if(ArrayUtils.contains(userIds, loginUserId(authentication))){
			return new ComResp().result("500","当前用户不能删除");
		}
		sysUserService.deleteBatch(userIds);
		return new ComResp().success();
	}


	@GetMapping("/{username}")
	public ComResp<UserDTO> queryByUsername(@PathVariable("username") String username){
		SysUserEntity userEntity = sysUserService.queryByUserName(username);
		UserDTO userDTO= UserDTO.builder().build();
		if(Objects.nonNull(userEntity)){
			BeanUtils.copyProperties(userEntity,userDTO);
			Set<String> userPermissions = shiroService.getUserPermissions(userEntity.getUserId());
			userDTO.setPermissions(userPermissions);
		}
		return new ComResp<UserDTO>().data(userDTO).success();
	}

	/**
	 * 查询用户登陆成功后的token
	 * @param username
	 * @return
	 */
	@GetMapping("/token/{username}")
	public ComResp<UserTokenDTO> queryUserLoginToken(@PathVariable("username") String username){
		LambdaQueryWrapper<SysUserTokenEntity> eq = Wrappers.<SysUserTokenEntity>lambdaQuery().eq(SysUserTokenEntity::getUserName, username);
		SysUserTokenEntity one = sysUserTokenService.getOne(eq);
		UserTokenDTO userTokenDTO= UserTokenDTO.builder().build();
		if(Objects.nonNull(one)){
			BeanUtils.copyProperties(one,userTokenDTO);
			return new ComResp<UserTokenDTO>().data(userTokenDTO).success();
		}
		return new ComResp<UserTokenDTO>().data(null).success();
	}

	/**
	 * 保存用户登陆成功后的token
	 * @param userTokenDTO
	 * @return
	 */
	@PostMapping("/saveUserLoginToken")
	public ComResp saveUserLoginToken(@RequestBody UserTokenDTO userTokenDTO){
		LambdaQueryWrapper<SysUserTokenEntity> eq = Wrappers.<SysUserTokenEntity>lambdaQuery().eq(SysUserTokenEntity::getUserName, userTokenDTO.getUsername());
		SysUserTokenEntity one = sysUserTokenService.getOne(eq);
		SysUserTokenEntity sysUserTokenEntity=new SysUserTokenEntity();
		sysUserTokenEntity.setUserName(userTokenDTO.getUsername());
		sysUserTokenEntity.setToken(userTokenDTO.getToken());
		if(Objects.isNull(one)){
			sysUserTokenService.save(sysUserTokenEntity);
		}else{
			sysUserTokenService.updateById(sysUserTokenEntity);
		}
		return new ComResp().success();
	}
}
